<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
    function runPromiseByQueue(myPromises) {
        myPromises.reduce(
            (prev, cur) => {
                console.log(cur);

                return prev.then(()=>{
                    return cur();
                });
            }
        ,Promise.resolve())
    }

    function createPromise(time, id){ 
        //返回一个函数构造器
        return ()=>{
            return new Promise((solve) =>{
                setTimeout(() => {
                    console.log("promise", id, new Date());
                    solve();
                }, time);
            });
        }
    }
        
    // async function test(){
    //     await createPromise(1000, 1);
    //     await createPromise(1000, 2);
    //     await createPromise(1000, 3);
    // }
    // 
    // test();

    var arr = [];
    arr.push(createPromise(3000, 1));
    arr.push(createPromise(2000, 2));
    arr.push(createPromise(1000, 3));

    console.log(new Date());

    runPromiseByQueue(arr);

    const list = [];

    for (let i = 0; i < 10; ++i) {
        list.push(i);
    }

    function PromiseForEach(arr, cb) {
        let realResult = []

        // Promise.resolve方法允许调用时不带参数，直接返回一个resolved状态的 Promise 对象。
        let result = Promise.resolve()

        arr.forEach((a, index) => {
            result = result.then(() => {
                return cb(a).then((res) => {
                    //realResult.push(res)
                })
            })
        })

        return result.then(() => {
            return realResult
        })
    }

    // PromiseForEach(list, (number) => {
    //     return new Promise((resolve, reject) => {
    //         setTimeout(() => {
    //             console.log(number);
    //             resolve(number);
    //         }, 100);
    //     })

    // }).then((data) => {
    //     console.log("成功");
    //     console.log(data);
    // }).catch((err) => {
    //     console.log("失败");
    //     console.log(err)
    // }); 
    </script>
</body>
</html>